import api from "./api/index.js"
import { userAuthList } from "@/Auth/user.js"
import { apiGetWarehouseInventoryList, skuOwnerInventory } from "@/api/public"
import { cloneDeep } from "lodash"
// export const pageComfig = ref({})
// 页面 配置项
export const pageComfig = ref({
  type: "list", // 页面类型
  isShowLeft: false, // 左边栏状态
  showOrderProfit: false, //
})
const statusColor = {
  未标记: "bg-[#FAAD14]",
  标记中: "bg-[#6C7283]",
  已标记: "bg-[#3487FF]",
  标记失败: "bg-[#E50113]",
  不标记: "bg-[#CDCFD4]",
}
// 买家评价 字体颜色
const commentColor = {
  Positive: "text-green",
  Neutral: "text-blue",
  Negative: "text-red",
}
const recipientJoin = ["recipient_country", "recipient_province", "recipient_zip_code", "recipient_city", "recipient_region", "recipient_preferred_address", "recipient_secondary_address"]
// 操作
export const handleFunctions = ref({})

const remarkConfig = [
  { label: "买家留言", field: "buyer_remark", show: true, edit: false },
  { label: "订单备注", field: "order_remark", light: true, show: true, edit: true },
  { label: "发货备注", field: "shipping_remark", edit: true },
  { label: "客服备注", field: "customer_service_remark", edit: true },
  { label: "物流备注", field: "logistics_remark", edit: true },
]

const countryFlag = {
  uk: "gb",
}
export const getFlag = (country) => {
  return countryFlag[country] || country
}
const openExpandLogistics = (row) => {
  row.expandLogistics = !row.expandLogistics
  handleFunctions.value.rendererView()
}
export const tableOptinos = reactive({
  api: api.getList,
  cellStyle: ({ row, column }) => {
    // if (!row?.order_sn) {
    //   console.log(12)
    //   return {
    //     height: "10px",
    //   }
    // }

    // 问题订单
    let cellStyle = {
      paddingTop: "8px",
    }
    if (row?.problem_cause_id_desc?.length) {
      cellStyle.paddingBottom = "36px"
    } else {
      cellStyle.paddingBottom = "16px"
    }
    // 退款订单 标红
    if (column.title == "订单金额" && row?.refund_status != 0) {
      cellStyle.backgroundColor = "#fce5e7"
    }
    return cellStyle

    // console.log( document.getElementsByClassName(row.id)?.[0]?.clientHeight);

    // return {
    //   height: document.getElementsByClassName(row.id)?.[0]?.clientHeight + "px",
    // }
    // console.log(row);
    // console.log(document.getElementById(`${row.id}-order-can-merged`));
    // console.log(document.getElementById(`${row.id}-order-can-merged`)?.clientHeight)
    // let height = document.getElementById(`${row.id}-order-can-merged`)?.clientHeight
    // // height < 150 && (height = 186)
    // // height < 150 && (height = 186)
    // // console.log(height)
    // if (!height || height < 170) {
    //   // console.log(100998)
    //   // console.log(height);
    //   // height = 188
    //   height = row.expandLogistics ? 232 : 170
    //   // console.log(height)
    // } else {
    //   // console.log(10086);
    //   // console.log(row.order_sn);
    //   height = height
    // }
    // let cellStyle = {
    //   // height: height + "px!important",
    //   height: height + "px",
    //   // boxSizing: 'border-box'
    //   boxSizing: "content-box",
    // }

    // row?.problem_cause_id_desc?.length && (height = height + 40)
    // console.log(height)
    // return {
    //   height: height + "px",
    // }

    // let height = 186
    // // 发货信息 展开
    // // row.expandLogistics && (height = 250)
    // // 商品信息展开
    // let height1 = document.getElementById(`${row.id}-order-can-merged`)?.clientHeight + 16
    // // height = row.expandStatus && row?.items?.length > 1 ? 144 * row?.items?.length + 52 : height
    // height = row.expandStatus ?  (row?.items?.length > 1 ? height1 : height) : 186
    // row?.problem_cause_id_desc?.length && (height = height + 28)
    // return {
    //   height: `${height}px`,
    //   "padding-bottom": row?.problem_cause_id_desc?.length ? "20px" : "8px",
    // }
  },
  setWarehouseParams: async (data) => {
    const newTableData = cloneDeep(data)
    let warehouseParams = data.reduce((pre, cur) => {
      const { id, warehouse_id = "" } = cur
      if (cur.items && cur.items.length) {
        let skus = cur.items.filter((v) => v.sku)
        skus = skus.map((v) => ({ item_sku: v.sku, warehouse_id: warehouse_id }))
        pre = [...pre, ...skus]
        pre = Array.from(new Set(pre.map((item) => JSON.stringify(item)))).map((item) => JSON.parse(item))
      }
      return pre
    }, [])
    let res = await apiGetWarehouseInventoryList({ data: warehouseParams })
    newTableData.forEach((item) => {
      item.items?.forEach((items) => {
        try {
          res.data.forEach((val) => {
            if (`${val.item_sku}_${val.warehouse_id}` == `${items.sku}_${item.warehouse_id}`) {
              items.available_stock = val.inventory
              throw Error()
            }
          })
        } catch (error) {}
      })
    })
    // console.log(newTableData);
    return newTableData
    // let warehouseParams = data.reduce((pre, cur) => {
    //   const { id, warehouse_id = "" } = cur
    //   if (cur.items && cur.items.length) {
    //     const skus = cur.items
    //       .filter((v) => v.sku)
    //       .map((v) => ({
    //         // rowId: v.id,
    //         // asin:v.asin,  // owner_id: 货主
    //         item_sku: v.sku,
    //         owner_id: v.sales_id, // owner_id: 货主
    //         warehouse_id: warehouse_id,
    //       }))
    //     pre = [...pre, ...skus]
    //     pre = Array.from(new Set(pre.map((item) => JSON.stringify(item)))).map((item) => JSON.parse(item))
    //   }
    //   return pre
    // }, [])
    // let res = await skuOwnerInventory({ data: warehouseParams })
    // // console.time(111)
    // newTableData.forEach((item) => {
    //   item.items?.forEach((items) => {
    //     try {
    //       res.data.forEach((val) => {
    //         if (`${val.item_sku}_${val.owner_id}_${val.warehouse_id}` == `${items.sku}_${items.sales_id}_${item.warehouse_id}`) {
    //           items.available_stock = val.inventory
    //           throw Error()
    //         }
    //       })
    //     } catch (error) {}
    //   })
    // })
    // // console.timeEnd(111)
    // return newTableData
  },

  columns: [
    {
      title: "订单信息",
      minWidth: 240,
      // fixed: "left",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="flex">
                <span class="flex-1 flex items-center">
                  <VText value={row.order_sn} type="link" copy={true} onClick={() => handleFunctions?.value?.handleDetail(row.id)} />
                </span>
                {row.platform_id == 1 ? (
                  <span class="cursor-pointer split-order mr-[4px]" style="background:#3487FF" onClick={() => handleFunctions?.value?.gotoWrite(row)}>
                    邮件
                  </span>
                ) : (
                  ""
                )}
                {row.is_original_order ? (
                  <span class="cursor-pointer split-order mr-[4px] " style="background:#3487FF">
                    原单
                  </span>
                ) : (
                  ""
                )}

                {row.is_consolidate_order == 1 ? (
                  <span class="cursor-pointer consolidate-order" onClick={() => handleFunctions?.value?.gotoConsolidateOrder(row)}>
                    合并
                  </span>
                ) : (
                  ""
                )}
                {row.is_split_order == 1 ? <span class="cursor-pointer split-order">拆分</span> : ""}
              </div>

              <VText title="平台订单号" value={row.platform_order_sn} copy={true}></VText>
              {/* 沃尔玛 、 ebay */}
              {[1, 4].includes(row.platform_id) ? <VText title="交易号" value={row?.payment?.transaction_no} line={1} copy={true} /> : ""}
              <VText title="平台/站点" value={`${row.platform}/${row.site}`} line={1} />
              <VText title="店铺" value={row.shop} line={1} class="text-warning" copy={true} />
              {row.platform_id == 1 && row?.recipient?.buyer_name ? <VText title="买家姓名" value={row?.recipient?.buyer_name} line={1} class="text-green" copy={true} /> : ""}

              <VText title="发货类型" value={row.shipping_type_desc} line={1} />

              <div class="el-button-wrap flex items-center">
                <span class="flex items-center text-[#3487ff] btn-item" v-hasPermi={[[userAuthList[pageComfig.value.type].edit]]} onClick={() => handleFunctions?.value?.handleEdit(row.id)}>
                  <svg-icon icon-class="edit_icon" class="mr-[2px]" />
                  <el-link underline={false} type="primary">
                    编辑
                  </el-link>
                </span>
                {/* <el-divider direction="vertical" />≥ */}
                <span class="flex items-center text-[#3487ff] btn-item" v-hasPermi={[[userAuthList[pageComfig.value.type].copy]]} onClick={() => handleFunctions?.value?.handleCopy(row)}>
                  <svg-icon icon-class="copy" class="mr-[2px]" />
                  <el-link underline={false} type="primary">
                    复制
                  </el-link>
                </span>
                {/* <el-divider direction="vertical" /> */}
                <span class="flex items-center text-[#3487ff] btn-item" v-hasPermi={[[userAuthList[pageComfig.value.type].log]]} onClick={() => handleFunctions?.value?.handleLog(row)}>
                  <svg-icon icon-class="rizhi" class="mr-[2px]" />
                  <el-link underline={false} type="primary">
                    日志
                  </el-link>
                </span>
              </div>
            </div>
          )
        },
      },
    },
    { title: "商品信息", width: 440, slots: { default: "Goods" } },
    {
      title: "订单状态",
      minWidth: 170,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="flex items-center justify-between mb-1">
                <div class={["text-[16px] font-[500]", ["问题订单", "采购缺货", "取消订单"].includes(row.order_status_desc) ? "text-[red]" : "title-color"]}>{row.order_status_desc}</div>
                <div class={["text-[#fff] px-[2px] rounded-[5px] scale-[0.8]", statusColor[row.mark_shipment_status_desc] || "bg-[#FAAD14]"]}>{row.mark_shipment_status_desc}</div>
              </div>
              <VText title="付款状态" value={row.pay_status_desc} line={1} />
              <VText title="发货状态" value={row.shipping_status_desc} line={1} />
              {row.platform == "ebay" && row.ascription_extend ? <VText title="Ebay订单站点" value={row.ascription_extend} line={1} /> : ""}

              <VText title="平台订单状态" value={row.platform_order_status_desc} line={2} />

              {row?.platform_order_type?.map((val) => (
                <p class="mt-1 mb-1">
                  <span class="text-[red] text-[14px] bg-[#FFE5E5] py-[2px] px-[10px] text-center rounded-[12px]">{val}</span>
                </p>
              ))}
            </div>
          )
        },
      },
    },

    {
      title: "订单金额",
      minWidth: 170,
      slots: { default: "OrderPrice" },
      // slots: {
      //   default: ({ row }) => {
      //     return (
      //       <div>
      //         <div class="flex items-center ">
      //           <country-flag country={getFlag(row?.recipient?.recipient_country?.toLowerCase())} class="mr-[6px] mb-2" size="big" shadow />
      //           <div>{row.recipient.country_cn}</div>
      //         </div>

      //         <VText title="支付金额" value={`${row.original_order_currency} ${row.original_order_amount || "0"}`} line={1} />
      //         <VText title="产品总价" value={`${row.original_order_currency} ${row.order_amount || "0"}`} line={1} />
      //         {/* 退款状态 */}
      //         {row?.refund_status != 0 ? (
      //           <span class="text-red">
      //             <VText title={row.refund_status_desc} value={`${row.original_order_currency} -${row?.payment?.refund_amount_tax}`} line={1} />
      //           </span>
      //         ) : (
      //           ""
      //         )}

      //         {row?.shipping_revenue ? <VText title="运费收入" value={row.shipping_revenue ? `${row.original_order_currency} ${row.shipping_revenue}` : ""} line={1} /> : ""}

      //         {row?.discount_amount ? <VText title="优惠金额" value={row.discount_amount ? `${row.original_order_currency} ${row.discount_amount}` : ""} line={1} /> : ""}

      //         {row?.other_price ? <VText title="其他收入" value={row.other_price ? `${row.original_order_currency} ${row.other_price}` : ""} line={1} /> : ""}

      //         {row?.tax_amount ? <VText title="税费收入" value={row.tax_amount ? `${row.original_order_currency} ${row.tax_amount}` : ""} line={1} /> : ""}

      //         {handleFunctions?.value?.isShowOrderProfit() ? (
      //           <div class="flex items-center">
      //             <div>
      //               <VText title="利润" value={row.total_order_profit ? `CNY ${row.total_order_profit}` : "0"} line={1} class={row.total_order_profit < 0 ? "text-red" : ""} />
      //             </div>
      //             <div class="flex-1 ml-[4px]">
      //               <div
      //                 class={`w-[24px] h-[14px] text-[10px] text-[#fff] border-radius-[2px] px-[1px] align-center ${row.settlement_status == 1 ? "bg-[#3487FF]" : "bg-[#FF6334]"}`}
      //                 style="line-height: 14px;"
      //               >
      //                 {row.settlement_status == 1 ? "真实" : "预估"}
      //               </div>
      //             </div>
      //           </div>
      //         ) : (
      //           ""
      //         )}

      //         {handleFunctions?.value?.isShowOrderProfit() ? (
      //           <VText title="利润率" value={row.total_order_profit_rate ? `${(row.total_order_profit_rate * 100).toFixed(2)}%` : "0"} line={1} class={row.total_order_profit_rate < 0 ? "text-red" : ""} />
      //         ) : (
      //           ""
      //         )}
      //       </div>
      //     )
      //   },
      // },
    },

    {
      title: "发货信息",
      minWidth: 240,
      slots: {
        default: ({ row }) => {
          let recipienttext = recipientJoin.map((k) => row?.recipient?.[k])
          recipienttext = `${recipienttext?.filter(Boolean).join("/")} ${row?.recipient?.recipient_door_num} / ${row?.recipient?.recipient_name} ${row?.recipient?.recipient_last_name}`
          return (
            <div>
              <VText title="地址" value={recipienttext || "-"} type="link" line={1} onClick={() => handleFunctions?.value?.openRecipientDtl(row)} copy={true} />

              <VText title="平台运输方式" value={row.platform_shipping_method} line={1} />
              <VText title="策略" value={row.order_strategy_name} line={1} />
              <VText title="发货仓库" value={row?.logistics?.ship_warehouse_name} line={1} />
              <VText title="运输方式" value={row?.logistics?.transport_name} line={1} />
              <VText title="真实追踪号" value={row?.logistics?.real_track_no} line={1} copy={true} />

              {row?.logistics?.overseas_wms_out_number ? <VText title="海外仓出库单号" value={row?.logistics?.overseas_wms_out_number} line={1} copy={true} /> : ""}
              {row?.logistics?.tracking_number ? <VText title="标记追踪号" value={row?.logistics?.tracking_number} line={1} copy={true} /> : ""}

              {/* 物流商单号与追踪号一致时，隐藏物流商单号，只显示真实追踪号 */}
              {row?.logistics?.logistics_bill_num && row?.logistics?.logistics_bill_num != row?.logistics?.real_track_no ? (
                <VText title="物流商单号" value={row?.logistics?.logistics_bill_num} line={1} />
              ) : (
                ""
              )}
              {row?.logistics?.logistics_transfer_num ? <VText title="物流商转单号" value={row?.logistics?.logistics_transfer_num} line={1} /> : ""}

              {row?.logistics?.return_number ? <VText title="回邮单号" value={row?.logistics?.return_number} line={1} copy={true} /> : ""}

              {row.expandLogistics ? (
                <div>
                  <span class="flex">
                    <span class="flex-1 mr-[6px]">
                      <VText title="SKU数" class="s-item" value={row.sku_num} line={1} />
                    </span>
                    <VText title="产品数" class="s-item" value={row.order_product_num} line={1} />
                  </span>

                  <span class="flex">
                    <span class="flex-1 mr-[6px]">
                      <VText title="体积" class="s-item" value={`${row?.logistics?.volume || 0}cm³`} line={1} />
                    </span>
                    <VText title="重量" class="s-item" value={`${row?.logistics?.estimated_weight || 0}g`} />
                  </span>

                  <VText title="抛率" class="s-item" value={row?.logistics?.throw_rate} line={1} />
                  <p>
                    <el-link type="primary" icon="Document" onClick={() => handleFunctions?.value?.openDeclare(row)}>
                      <span>申报信息</span>
                    </el-link>
                  </p>
                </div>
              ) : (
                ""
              )}
              <el-link type="primary" onClick={() => openExpandLogistics(row)}>
                <span>{row.expandLogistics ? "收起" : "展开"}</span>
                <svg-icon icon-class="arrow_down" class={row.expandLogistics ? "rotate-[180deg]" : ""} />
              </el-link>
            </div>
          )
        },
      },
    },

    {
      title: "备注信息",
      minWidth: 200,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.order_comment.length > 0 ? (
                <div class="flex">
                  <div>
                    <VText title="买家评价" value=" " />
                  </div>

                  <div class="flex-1">
                    {row.order_comment?.map((item, i) => (
                      <span>
                        <span class={commentColor[item.comment_type]}>{item.comment_type_desc}</span>
                        {i != row.order_comment.length - 1 ? <span>/</span> : ""}
                      </span>
                    ))}
                  </div>
                </div>
              ) : (
                ""
              )}

              {remarkConfig?.map((item) => (
                <div>
                  {item.show || row[item.field] ? (
                    <div>
                      <p class={["r-title text-[var(--base-sub-text-color)]"]}>{item.label}：</p>
                      <p class={["text-[var(--base-text-color)] flex", item.light ? "line-clamp" : ""]} onClick={() => handleFunctions?.value?.editRemark(row, item)}>
                        {item.edit ? <svg-icon icon-class="edit_icon" class="text-[#3487ff] inline mt-[4px]" /> : ""}
                        <div class="flex-1 w-[100%]">{item.edit ? <VText value={row[item.field]} line={item.show ? 100 : 3} class="text-blue" /> : row[item.field]}</div>
                      </p>
                    </div>
                  ) : (
                    ""
                  )}
                </div>
              ))}
            </div>
          )
        },
      },
    },

    {
      title: "时间",
      minWidth: 240,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText title="下单" value={row.order_time} line={1} />
              <VText title="添加" value={row.create_time} line={1} />
              <VText title="修改" value={row.update_time} line={1} />
              {row.shipping_time ? <VText title="发货" value={row.shipping_time} line={1} /> : ""}
              {row.marking_time ? <VText title="标发" value={row.marking_time} line={1} /> : ""}

              <VText title="剩余发货" value={row.delivery_time_limit} line={1} class="t-info" />
              <VText title="追踪号有效期" value={row.tracking_number_expiry_date} line={1} class="t-info" />
            </div>
          )
        },
      },
    },

    {
      title: "操作人员",
      minWidth: 180,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText title="添加" value={row.create_user} line={1} />
              <VText title="修改" value={row.update_user} line={1} />
              <VText title="客服" value={row.customer_service} line={1} />
              <VText title="销售" value={row.sales?.join() || ""} line={1} />
            </div>
          )
        },
      },
    },
  ],
})

// 可合并订单
export const OrderCanMergedTableOptinos = reactive({
  api: api.canMergedIndex,
  cellStyle: ({ row, column }) => {
    return {
      height: document.getElementById(`${row?.id}-order-can-merged`)?.clientHeight + 16 + "px",
    }
  },
  setWarehouseParams: async (data) => {
    const newTableData = cloneDeep(data)

    let warehouseParams = data.map((v) => v.child).flat(1)
    warehouseParams = warehouseParams.reduce((pre, cur) => {
      const { id, warehouse_id } = cur
      if (cur.items && cur.items.length) {
        const skus = cur.items.reduce((preItems, curItems) => {
          const { sku } = curItems
          if (!preItems.includes[sku]) preItems.push(sku)
          return preItems
        }, [])
        const arrs = skus.map((skuItem) => {
          const dtd = { item_sku: skuItem, rowId: id, warehouse_id: warehouse_id }
          // const _find = pre.find((f) => f.item_sku === skuItem && f.warehouse_id === warehouse_id)
          // if (!_find) {
          //   if (warehouse_id) dtd.warehouse_id = warehouse_id
          // }
          return dtd
        })
        pre = [...pre, ...arrs]
      }
      return pre
    }, [])
    let res = await apiGetWarehouseInventoryList({ data: warehouseParams })

    newTableData.forEach((item) => {
      res.data.forEach((row) => {
        const { rowId, item_sku, inventory } = row
        const _findIndex = item.child.findIndex((v) => v.id === rowId)
        if (_findIndex > -1) {
          const { items } = item.child[_findIndex]
          if (items && Array.isArray(items)) {
            const _findSkuItemIndex = items.findIndex((v) => v.sku === item_sku)
            if (_findSkuItemIndex > -1) {
              item.child[_findIndex].items[_findSkuItemIndex].available_stock = inventory
            }
          }
        }
      })
    })
    return newTableData

    // console.time(222)
    // let warehouseParams = data.map((v) => v.child).flat(1)
    // console.log(warehouseParams)
    // warehouseParams = warehouseParams.reduce((pre, cur) => {
    //   const { id, warehouse_id } = cur
    //   if (cur.items && cur.items.length) {
    //     const skus = cur.items
    //       .filter((v) => v.sku)
    //       .map((v) => ({
    //         // rowId: v.id,
    //         // asin:v.asin,  // owner_id: 货主
    //         item_sku: v.sku,
    //         owner_id: v.sales_id, // owner_id: 货主
    //         warehouse_id: warehouse_id,
    //       }))

    //     pre = [...pre, ...skus]
    //     pre = Array.from(new Set(pre.map((item) => JSON.stringify(item)))).map((item) => JSON.parse(item))
    //   }
    //   return pre
    // }, [])
    // console.timeEnd(222)
    // let res = await skuOwnerInventory({ data: warehouseParams })
    // console.time(111)
    // newTableData.forEach((row) => {
    //   row.child?.forEach((item) => {
    //     item.items?.forEach((items) => {
    //       if (items.sku) {
    //         try {
    //           res.data.forEach((val) => {
    //             if (`${val.item_sku}_${val.owner_id}_${val.warehouse_id}` == `${items.sku}_${items.sales_id}_${item.warehouse_id}`) {
    //               items.available_stock = val.inventory
    //               throw Error()
    //             }
    //           })
    //         } catch (error) {}
    //       }
    //     })
    //   })
    // })
    // console.timeEnd(111)
    // // console.log(newTableData)
    // return newTableData
  },

  columns: [
    {
      title: "订单信息",
      params: "left",
      width: 150,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class=" px-[8px]">
                <div class="flex-1">
                  <label>总体积：</label>
                  <span class="value">{row?.volume || "-"}cm³</span>
                </div>
                <div>
                  <label>总重量：</label>
                  <span class="value">{row?.total_weight || "-"}g</span>
                </div>
              </div>
            </div>
          )
        },
      },
    },
    {
      title: "合并方式",
      params: "left",
      width: 170,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.child?.map((item) => (
                <div class="order-row line">
                  <div class="order-item" style={{ height: item.expandStatus ? `${138 * item.items?.length || 1}px` : `138px` }}>
                    <el-select v-model={item.canMerged} placeholder="请选择" class="w-[100%]">
                      {[...Array(row.child?.length - 1)]?.map((v, i) => (
                        <el-option label={`合并${i + 1}组`} value={i + 1} />
                      ))}
                      <el-option label="不合并" value="0" />
                    </el-select>
                  </div>
                </div>
              ))}
            </div>
          )
        },
      },
    },
    {
      title: "订单信息",
      width: 220,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.child?.map((item) => (
                <div class="order-row line">
                  <div class="order-item" style={{ height: item.expandStatus ? `${138 * item.items?.length || 1}px` : `138px` }}>
                    <VText value={item.order_sn} type="link" copy={true} />
                    <VText title="平台订单号" value={item.platform_order_sn} />
                    <VText title="平台/站点" value={`${item.platform}/${item.site}`} />
                    <VText title="店铺" value={item.shop} />
                  </div>
                </div>
              ))}
            </div>
          )
        },
      },
    },
    { title: "商品信息", width: 400, slots: { default: "OrderCanMergedTem" } },
    {
      title: "订单金额",
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.child?.map((item) => (
                <div class="order-row line">
                  <div class="order-item" style={{ height: item.expandStatus ? `${138 * item.items?.length || 1}px` : `138px` }}>
                    <div class="text-[18px] font-bold value">
                      {item.original_order_currency} {item.original_order_amount}
                    </div>
                    <VText title="产品总价" value={`${item.original_order_currency} ${item.order_amount}`} />
                    <VText title="运费收入" value={`${item.original_order_currency} ${item.shipping_revenue}`} />
                  </div>
                </div>
              ))}
            </div>
          )
        },
      },
    },
    {
      title: "订单发货信息",
      minWidth: 220,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.child?.map((item) => (
                <div class="order-row line">
                  <div class="order-item" style={{ height: item.expandStatus ? `${138 * item.items?.length || 1}px` : `138px` }}>
                    <VText title="发货仓库" value={item?.ship_warehouse_name} />
                    <VText title="运输方式" value={item?.shipping_logistics_attr} />
                    <VText title="真实追踪号" value={item?.logistics?.real_track_no} />
                    <span class="flex">
                      <span class="flex-1">
                        <VText title="SKU数" value={item?.sku_num} />
                      </span>
                      <VText title="产品数" value={item?.order_product_num} />
                    </span>
                    <span class="flex">
                      <span class="flex-1">
                        <VText title="体积" value={(item?.logistics?.volume || 0) + "cm³"} />
                      </span>
                      <VText title="重量" value={(item?.logistics?.estimated_weight || 0) + "g"} />
                    </span>
                  </div>
                </div>
              ))}
            </div>
          )
        },
      },
    },
    {
      title: "订单处理信息",
      minWidth: 250,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.child?.map((item) => (
                <div class="order-row line">
                  <div class="order-item" style={{ height: item.expandStatus ? `${138 * item.items?.length || 1}px` : `138px` }}>
                    <VText title="下单时间" value={item?.order_time} />
                    <VText title="下单时间" value={item?.update_time} />
                    <VText title="支付时间" value={item?.pay_time} />
                    <VText title="销售人员" value={item?.sales?.[0]} />
                  </div>
                </div>
              ))}
            </div>
          )
        },
      },
    },
    {
      title: "订单客户地址信息",
      minWidth: 240,
      slots: {
        default: ({ row }) => {
          return (
            <div class="pl-[16px]">
              <VText title="用户名" value={row.child?.[0]?.recipient?.clientele_id} />
              <VText title="收货人姓名" value={row.child?.[0]?.recipient?.recipient_name} />
              <VText title="收货人电话" value={row.child?.[0]?.recipient?.recipient_phone} />
              <VText title="收货人邮箱" value={row.child?.[0]?.recipient?.recipient_email} />
              <VText title="收货人国家" value={row.child?.[0]?.recipient?.recipient_country} />
              <VText title="收货人省/州" value={row.child?.[0]?.recipient?.recipient_province} />
              <VText title="收货人市/区" value={row.child?.[0]?.recipient?.recipient_region} />
              <VText title="邮编" value={row.child?.[0]?.recipient?.recipient_zip_code} />
              <VText title="门牌号" value={row.child?.[0]?.recipient?.recipient_door_num} />
              <VText title="客户备注" value={row.child?.[0]?.buyer_remark} />
            </div>
          )
        },
      },
    },
  ],
})

// 已合并订单
export const OrderMergedTableOptinos = reactive({
  api: api.mergedIndex,
  cellStyle: ({ row, column }) => {
    return {
      height: document.getElementById(`${row?.id}-order-can-merged`)?.clientHeight + 16 + "px",
    }
  },
  setWarehouseParams: async (data) => {
    // console.log(11222233)
    const newTableData = cloneDeep(data)

    let warehouseParams = data.map((v) => v.child).flat(1)
    warehouseParams = warehouseParams.reduce((pre, cur) => {
      const { id, warehouse_id } = cur
      if (cur.items && cur.items.length) {
        const skus = cur.items.reduce((preItems, curItems) => {
          const { sku } = curItems
          if (!preItems.includes[sku]) preItems.push(sku)
          return preItems
        }, [])
        const arrs = skus.map((skuItem) => {
          const dtd = { item_sku: skuItem, rowId: id, warehouse_id: warehouse_id }
          // const _find = pre.find((f) => f.item_sku === skuItem && f.warehouse_id === warehouse_id)
          // if (!_find) {
          //   if (warehouse_id) dtd.warehouse_id = warehouse_id
          // }
          return dtd
        })
        pre = [...pre, ...arrs]
      }
      return pre
    }, [])
    let res = await apiGetWarehouseInventoryList({ data: warehouseParams })
    newTableData.forEach((item) => {
      res.data.forEach((row) => {
        const { rowId, item_sku, inventory } = row
        const _findIndex = item.child.findIndex((v) => v.id === rowId)
        if (_findIndex > -1) {
          const { items } = item.child[_findIndex]
          if (items && Array.isArray(items)) {
            const _findSkuItemIndex = items.findIndex((v) => v.sku === item_sku)
            if (_findSkuItemIndex > -1) {
              item.child[_findIndex].items[_findSkuItemIndex].available_stock = inventory
            }
          }
        }
      })
    })
    return newTableData

    // console.time(222)
    // let warehouseParams = data.map((v) => v.child).flat(1)
    // console.log(warehouseParams)
    // warehouseParams = warehouseParams.reduce((pre, cur) => {
    //   const { id, warehouse_id } = cur
    //   if (cur.items && cur.items.length) {
    //     const skus = cur.items
    //       .filter((v) => v.sku)
    //       .map((v) => ({
    //         // rowId: v.id,
    //         // asin:v.asin,  // owner_id: 货主
    //         item_sku: v.sku,
    //         owner_id: v.sales_id, // owner_id: 货主
    //         warehouse_id: warehouse_id,
    //       }))

    //     pre = [...pre, ...skus]
    //     pre = Array.from(new Set(pre.map((item) => JSON.stringify(item)))).map((item) => JSON.parse(item))
    //   }
    //   return pre
    // }, [])
    // console.timeEnd(222)
    // let res = await skuOwnerInventory({ data: warehouseParams })
    // console.time(111)
    // newTableData.forEach((row) => {
    //   row.child?.forEach((item) => {
    //     item.items?.forEach((items) => {
    //       if (items.sku) {
    //         try {
    //           res.data.forEach((val) => {
    //             if (`${val.item_sku}_${val.owner_id}_${val.warehouse_id}` == `${items.sku}_${items.sales_id}_${item.warehouse_id}`) {
    //               items.available_stock = val.inventory
    //               throw Error()
    //             }
    //           })
    //         } catch (error) {}
    //       }
    //     })
    //   })
    // })
    // console.timeEnd(111)
    // return newTableData
  },
  columns: [
    {
      title: "订单信息",
      minWidth: 230,
      // width: 220,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.child?.map((item) => (
                <div class="order-row">
                  <div class="order-item" style={{ height: item.expandStatus ? `${138 * item.items?.length || 1}px` : `138px` }}>
                    <VText value={item.order_sn} type="link" copy={true} />
                    <VText title="平台订单号" value={item.platform_order_sn} />
                    <VText title="平台/站点" value={`${item.platform}/${item.site}`} />
                    <VText title="店铺" value={item.shop} />
                  </div>
                </div>
              ))}
            </div>
          )
        },
      },
    },
    { title: "订单商品", width: 400, slots: { default: "OrderMergedTem" } },

    {
      title: "订单金额",
      width: 220,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.child?.map((item) => (
                <div class="order-row line">
                  <div class="order-item" style={{ height: item.expandStatus ? `${138 * item.items?.length || 1}px` : `138px` }}>
                    <div class="text-[18px] font-bold value">
                      {item.original_order_currency} {item.original_order_amount}
                    </div>
                    <VText title="产品总价" value={item.original_order_currency} />
                    <VText title="运费收入" value={item.original_order_currency} />
                  </div>
                </div>
              ))}
            </div>
          )
        },
      },
    },

    {
      title: "订单处理信息",
      minWidth: 250,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.child?.map((item) => (
                <div class="order-row line">
                  <div class="order-item" style={{ height: item.expandStatus ? `${138 * item.items?.length || 1}px` : `138px` }}>
                    <VText title="下单时间" value={item.order_time} />
                    <VText title="修改时间" value={item.update_time} />
                    <VText title="支付时间" value={item.pay_time} />
                    <VText title="销售人员" value={item.sales?.[0]} />
                  </div>
                </div>
              ))}
            </div>
          )
        },
      },
    },

    {
      title: "订单发货信息",
      minWidth: 250,
      slots: {
        default: ({ row }) => {
          return (
            <div class="px-[16px]">
              <div class="flex items-center justify-between mb-1">
                <span class={["text-[16px]  font-[500]", "问题订单,采购缺货,取消订单".includes(row.order_status_desc) ? "text-[red]" : "text-[#333]"]}>{row.order_status_desc}</span>
              </div>
              <VText title="合并订单号" />
              <VText value={row.order_sn} type="link" copy={true} />
              <VText title="发货仓库" value={row?.logistics?.ship_warehouse_name} />
              <VText title="运输方式" value={row?.logistics?.shipping_method} />
              <VText title="真实追踪号" value={row?.logistics?.real_track_no} />
              <VText title="SKU数" value={row?.sku_num} />
              <VText title="产品数" value={row?.order_product_num} />
              <VText title="总体积" value={(row?.logistics?.volume || 0) + "cm³"} />
              <VText title="总重量" value={(row?.logistics?.estimated_weight || 0) + "g"} />
            </div>
          )
        },
      },
    },

    {
      title: "订单客户地址信息",
      width: 240,
      slots: {
        default: ({ row }) => {
          return (
            <div class="px-[16px]">
              <VText title="用户名" value={row?.recipient?.clientele_id} />
              <VText title="收货人姓名" value={row?.recipient?.recipient_name} />
              <VText title="收货人电话" value={row?.recipient?.recipient_phone} />
              <VText title="收货人邮箱" value={row?.recipient?.recipient_email} />
              <VText title="收货人国家" value={row?.recipient?.recipient_country} />
              <VText title="收货人省/州" value={row?.recipient?.recipient_province} />
              <VText title="收货人市/区" value={row?.recipient?.recipient_region} />
              <VText title="邮编" value={row?.recipient?.recipient_zip_code} />
              <VText title="门牌号" value={row?.recipient?.recipient_door_num} />
              <VText title="客户备注" value={row?.buyer_remark} />
            </div>
          )
        },
      },
    },
  ],
})
